﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using HealthMonitor.Models;
using Orchard.ContentManagement;
using Orchard.ContentManagement.MetaData;
using Orchard.ContentManagement.MetaData.Models;
using Orchard.Core.Common.Fields;
using Orchard.Core.Contents.Settings;
using Orchard.Themes;
using Orchard.Fields.Fields;

namespace HealthMonitor.Controllers
{
    //http://dllhell.net/2011/08/15/on-creating-an-orchard-module-without-having-to-rtfm/
    [Themed]
    public class HomeController : Controller
    {
        readonly IContentManager _contentManager;
        readonly IContentDefinitionManager _contentDefinitionManager;

        public HomeController(IContentManager contentManager, IContentDefinitionManager contentDefinitionManager)
        {
            _contentManager = contentManager;
            _contentDefinitionManager = contentDefinitionManager;
        }

        public ActionResult Index(int? id=null)
        {
            if(id.HasValue==false)
            return View();
            var list = _contentManager.Get(id.Value);
            if (list == null)
                return Content("Did not find:" + id.Value);
            var model = new[] {list};

            return View("List", model);
        }

        public ActionResult ListAll(bool? creatable=false) {

            var query = _contentManager.Query(VersionOptions.Latest, GetCreatableTypes(creatable.GetValueOrDefault()).Select(ctd => ctd.Name).ToArray());
            return View("List", query.List().ToArray());
        }

        public ActionResult ListHealth(string typeName) {
            var query = _contentManager.Query(VersionOptions.Latest, typeName);
            if (query.Count() == 0)
                return View("List", new string[] {});
            var item = query.List().First();

            return View("List", new[] {item});
        }

        public ActionResult List(string list = "HealthUrl")
        {
            
            var q2 = _contentManager.Query(VersionOptions.Latest, list);
            var all = q2.List().ToArray();
            if (!all.Any())
                return Content("Unable to find any:" + list);
            var data= all.Select(hu => hu.Parts.FirstOrDefault(p => p.Fields.Any())).Where(hu => hu != null)
                .Select(p => new {Name=(p.Fields.First(f => f is TextField) as TextField) .Value,Link= (p.Fields.First(f => f is LinkField) as LinkField).Value});
            using (var c = new WebClient())
            {
                var q = data != null ? data.Where(s => String.IsNullOrEmpty(s.Link) == false && string.IsNullOrWhiteSpace(s.Link) == false).Select(s =>
                {
                    string response;
                    try
                    {
                        var reqResult = c.DownloadString(s.Link);
                        response = c.ResponseHeaders.ToString();
                    }
                    catch (WebException wex)
                    {
                        response = wex.ToString();

                    }


                    return new UriInfo(s.Name, new Uri(s.Link), response);
                }).ToArray() : new UriInfo[] { };

                return View(q);

            }
        }

        private IEnumerable<ContentTypeDefinition> GetCreatableTypes(bool andContainable)
        {
            return _contentDefinitionManager.ListTypeDefinitions().Where(ctd => ctd.Settings.GetModel<ContentTypeSettings>().Creatable && (!andContainable || ctd.Parts.Any(p => p.PartDefinition.Name == "ContainablePart")));
        }

        public ActionResult Health(string environment, string[] sites)
        {

            using (var c = new WebClient())
            {
                var q = sites != null ? sites.Where(s => String.IsNullOrEmpty(s) == false && string.IsNullOrWhiteSpace(s) == false).Select(s =>
                {
                    string response;
                    try
                    {
                        var reqResult = c.DownloadString(s);
                        response = c.ResponseHeaders.ToString();
                    }
                    catch (WebException wex)
                    {
                        response = wex.ToString();

                    }


                    return new UriInfo(s,new Uri(s),  response);
                }).ToArray() : new UriInfo[] { };

                return View(new EnvironmentInfo(environment, q));

            }

        }
    }
}